package org.example.ui;

import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.example.ClientServer;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class ChatUi extends JFrame {

    private JTextArea chatArea;
    private JTextField messageField;
    private JButton sendButton;
    @Getter
    @Setter
    String message;

    public ChatUi() {
        // 初始化聊天界面
        setTitle("Chat Application");
        setSize(400, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 聊天区域
        chatArea = new JTextArea();
        chatArea.setEditable(false); // 禁止编辑
        JScrollPane scrollPane = new JScrollPane(chatArea);

        // 输入消息区域
        messageField = new JTextField(25);
        sendButton = new JButton("Send");

        // 消息输入和发送按钮布局
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(new BorderLayout());
        inputPanel.add(messageField, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);

        // 将聊天区域和输入区域加入到主框架中
        add(scrollPane, BorderLayout.CENTER);
        add(inputPanel, BorderLayout.SOUTH);

        // 发送按钮的事件监听器
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        // 回车键发送消息
        messageField.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
    }

    // 发送消息的方法
    private void sendMessage() {
        String message = messageField.getText().trim();
        if (!message.isEmpty()) {
            chatArea.append("You: " + message + "\n");
            messageField.setText("");
            // 模拟回应
            chatArea.append("Bot: " + generateResponse(message) + "\n");
        }
    }

    // 简单的自动回复功能
    private String generateResponse(String message) {
        if (message.equalsIgnoreCase("hello")) {
            return "Hi there!";
        } else if (message.equalsIgnoreCase("how are you?")) {
            return "I'm a program, so I don't have feelings, but thanks for asking!";
        } else {
            return "Sorry, I don't understand that.";
        }
    }


}
